import { reqUserLogin,reqLogout } from "../../api";

const state = {
  userInfo: {
    name: localStorage.getItem("name"),
    token: localStorage.getItem("token"),
  },
};
const actions = {
  async userLogin({ commit }, user) {
    const result = await reqUserLogin(user);
    if (result.code === 200) {
      commit("SAVE_USER_DATA", result.data);
      return true
    } else {
      console.log(result.data);
    }
  },
  async userLogout({commit}){
    const result = await reqLogout()
    if(result.code===200){
      localStorage.removeItem('name')
      localStorage.removeItem('token')
      commit('REMOVE_USER_INFO')
    }else{
      console.log(result.message)
    }
  }
};
const mutations = {
  SAVE_USER_DATA(state, payload) {
    state.userInfo.name = payload.name;
    state.userInfo.token = payload.token;
    // 为了有一个更好的用户体验，在用户刷新页面的时候，也会有token
    // 此时可以在本地存储当中也存储一份
    localStorage.setItem('name', payload.name)
    localStorage.setItem('token',payload.token)
  },
  REMOVE_USER_INFO(state){
    state.userInfo.name=''
    state.userInfo.token=''
  }
};
const getters = {};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};
